const router = require('koa-router')()
const Redis = require('koa-redis')
// 引入数据库模型
const Person = require('../dbs/models/person')

const Store = new Redis().client //拿到redis客户端

router.prefix('/users')

router.get('/', function (ctx, next) {
  ctx.body = 'this is a users response!'
})

router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})

router.get('fix',async function(ctx){
  const st = await Store.hset('fix','name',Math.random())
  ctx.body = {
    code:0,
    st
  }
})

// 新建一个增加个人信息的路由
// post方式
router.get("/addPerson",async function(ctx){
  // ctx.body = 'this is a users/addPerson response'
  console.log(ctx);
  
  // 给Person新建一个实例
  const person = new Person({
    name:"lilei",
    ages:27
  })
  
  try{
    await person.save()
    code =0
  }catch(e){
    code = -1
  }
  ctx.body={
    code:code
  }
})
// 查询
router.post("getPerson",async function(ctx){
  const result = await Person.findOne({name:'lilei'});
  const results = await Person.find({name:'lilei'});
  try{
    ctx.body = {
      code:0,
      result,
      results
    }
  }catch(e){
    ctx.body = {
      code:-1
    }
  }
})
// 更新
router.post("updatePerson", async function(ctx){
  const result =  await Person.where({
    name:'lilei'
  }).update({
    age:30
  })
  try{
    ctx.body = {
      code:0,
      result
    }
  }catch(e){
    ctx.body = {
      code:-1
    }
  }
})
// 删除
router.post("updatePerson", async function(ctx){
  const result =  await Person.where({
    name:'lilei'
  }).remove()
  try{
    ctx.body = {
      code:0,
      result
    }
  }catch(e){
    ctx.body = {
      code:-1
    }
  }
})
module.exports = router
